//
//  HCTabbarViewController.m
//  MSHD
//
//  Created by HCreater on 2017/11/28.
//  Copyright © 2017年 HCreater. All rights reserved.
//

#import "HCTabbarViewController.h"
#import "HCMidBtnTabBar.h"

#import "MHNavigationController.h"

#import "LoginV2ViewController.h"
//
//#import "MainViewController.h"
//#import "Consultation4ProfessorViewController.h"
//#import "ConsultationViewController.h"
//#import "MyViewController.h"
//#import "PublicConsultationListViewController.h"
//#import "MyDocViewController.h"


@interface HCTabbarViewController () <UITabBarControllerDelegate>

@property (nonatomic, strong) HCMidBtnTabBar* hcTabBar;

@end

@implementation HCTabbarViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self _buildUI];
    
    @weakify(self);
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:Notify_Tabbar_Select object:nil] delay:0.2f] subscribeNext:^(id x) {
        @strongify(self);
        
        NSNotification* notify = x;
        
        NSInteger selectIndex = [notify.object integerValue];
        
        if (selectIndex == 2)
        {
            
        }
        else if (self.selectedIndex != selectIndex)
        {
            self.selectedIndex = selectIndex;
            
            UINavigationController* navvc = self.viewControllers[selectIndex];
            [navvc popToRootViewControllerAnimated:NO];
        }
    }];
    
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:Notify_Tabbar_BadgeNum object:nil] delay:0.2f] subscribeNext:^(id x) {
        @strongify(self);
        
        NSNotification* notify = x;
        
        NSDictionary* badgeInfo = notify.object;
        
        NSInteger selectIndex = [badgeInfo[@"ShowIndex"] integerValue];
        NSInteger badgeNum = [badgeInfo[@"BadgeNum"] integerValue];
        
        UITabBarItem* curTabbarItem = self.tabBar.items[selectIndex];
        
        NSString* strBadge = nil;
        if (badgeNum > 0)
        {
            strBadge = HCStrFormat(@"%d", (int)badgeNum);
        }
        curTabbarItem.badgeValue = strBadge;
    }];
    
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:Notify_LoginSuc object:nil] delay:0.2f] subscribeNext:^(id x) {
        @strongify(self);
        
        //Reset
//        UserManager* uMgr = [UserManager sharedUserManager];
//
//        MainViewModel* mainVM = [[MainViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"首页"}];
//        MainViewController* mainVC = [[MainViewController alloc] initWithViewModel:mainVM];
//        MHNavigationController* mainNav = [[MHNavigationController alloc] initWithRootViewController:mainVC];
//
//        MHNavigationController* consultationNav = nil;
//        if ([uMgr isLogined] && uMgr.userData.userType == 2)
//        {
//            Consultation4ProfessorViewModel* consultationVM = [[Consultation4ProfessorViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"环保咨询"}];
//            Consultation4ProfessorViewController* consultationVC = [[Consultation4ProfessorViewController alloc] initWithViewModel:consultationVM];
//            consultationNav = [[MHNavigationController alloc] initWithRootViewController:consultationVC];
//        }
//        else
//        {
//            ConsultationViewModel* consultationVM = [[ConsultationViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"环保咨询"}];
//            ConsultationViewController* consultationVC = [[ConsultationViewController alloc] initWithViewModel:consultationVM];
//            consultationNav = [[MHNavigationController alloc] initWithRootViewController:consultationVC];
//        }
//
//        MyViewModel* userCenterVM = [[MyViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"个人中心"}];
//        MyViewController* userCenterVC = [[MyViewController alloc] initWithViewModel:userCenterVM];
//        MHNavigationController* userCenterNav = [[MHNavigationController alloc] initWithRootViewController:userCenterVC];
//
//        [self setViewControllers:@[mainNav, consultationNav, userCenterNav]];
    }];
    
    [[self rac_signalForSelector:@selector(tabBar:didSelectItem:) fromProtocol:@protocol(UITabBarDelegate)] subscribeNext:^(id x)
    {
        RACTuple* tuple = x;
        
        HCMidBtnTabBar* tabbar = tuple.first;
        UITabBarItem* curItem = tuple.second;
        
        UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
        
        if (!curItem.title || [curItem.title isEqualToString:@""])
        {
            if (![um isLogined])
            {
                [self _presentLoginVC:-1];
            }
            else
            {
                [self _centerBtnAction:tabbar.centerBtn];
            }
        }
        else if (true)
        {
//            if (![um isLogined])
//            {
//                if ([curItem.title containsString:@"首页"])
//                {
//
//                }
//                else if ([curItem.title containsString:@"随手拍"])
//                {
//                    [self _presentLoginVC:1];
//                }
//                else if ([curItem.title containsString:@"咨询"])
//                {
//                    [self _presentLoginVC:3];
//                }
//                else if ([curItem.title containsString:@"个人"])
//                {
//                    [self _presentLoginVC:4];
//                }
//            }
//            else
//            {
            
//            }
            
            if ([curItem.title containsString:@"咨询"])
            {
                if (um.unReadMsgNum > 0)
                {
                    if ([um.userData.identify integerValue] == 2)
                    {
                        //进入对我答复界面
                        [self _push2AskMeVC];
                    }
                    else
                    {
                        //进入对我提问界面
                        [self _push2AskVC];
                    }
                    
                    //请求清除
                    [um cleanUnReadMsg];
                }
            }
            else if (![um isLogined])
            {
                if ([curItem.title containsString:@"个人"])
                {
                    [self _presentLoginVC:4];
                }
            }
        }
    }];
}

- (void)_buildUI
{
    _hcTabBar = [[HCMidBtnTabBar alloc] init];
    [_hcTabBar.centerBtn addTarget:self action:@selector(_centerBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    //选中时的颜色
    _hcTabBar.tintColor = [UIColor colorWithRed:27.0/255.0 green:118.0/255.0 blue:208/255.0 alpha:1];
    //透明设置为NO，显示白色，view的高度到tabbar顶部截止，YES的话到底部
    _hcTabBar.translucent = NO;
    //利用KVC 将自己的tabbar赋给系统tabBar
    [self setValue:_hcTabBar forKeyPath:@"tabBar"];
    
    self.delegate = self;
}

- (void)_centerBtnAction:(UIButton*)btn
{
//    [[NSNotificationCenter defaultCenter] postNotificationName:Notify_Tabbar_CenterBtn object:@{}];
    
    if (self.centerBtnBlock != nil)
    {
        self.centerBtnBlock(btn);
    }
}

// Delegate
//tabbar选择时的代理
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    //选中中间的按钮
    NSInteger shouldSelectIndex = [tabBarController.viewControllers indexOfObject:viewController];
    return shouldSelectIndex!=2;
}

// 交互
- (void)_presentLoginVC:(NSInteger)tabIndex
{
    if (tabIndex != -1)
    {
        UINavigationController* curNav = self.viewControllers[tabIndex];
        [curNav popToRootViewControllerAnimated:NO];
    }

    LoginV2ViewModel* vm = [[LoginV2ViewModel alloc] initWithParams:@{}];
    LoginV2ViewController* vc = [[LoginV2ViewController alloc] initWithViewModel:vm];

    MHNavigationController* lNav = [[MHNavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:lNav animated:YES completion:^
    {

    }];
}

- (void)_push2AskMeVC
{
//    UINavigationController* curNav = self.viewControllers[1];
//
//    [curNav popViewControllerAnimated:NO];
//
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0.3f), ^{
//
//        NSString* title = @"对我的咨询（未答复）";
//
//        PublicConsultationListViewModel* vm = [[PublicConsultationListViewModel alloc] initWithParams:@{SUViewModelTitleKey:title}];
//        vm.loadType = 3;
//        PublicConsultationListViewController* vc = [[PublicConsultationListViewController alloc] initWithViewModel:vm];
//
//        [curNav pushViewController:vc animated:YES];
//    });
}

- (void)_push2AskVC
{
//    UINavigationController* curNav = self.viewControllers[1];
//
//    [curNav popViewControllerAnimated:NO];
//
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0.3f), ^{
//
//        MyDocViewModel* vm = [[MyDocViewModel alloc] initWithParams:@{SUViewModelTitleKey:@"我的文档"}];
//        vm.tabIndex = 1;
//        MyDocViewController* vc = [[MyDocViewController alloc] initWithViewModel:vm];
//
//        [curNav pushViewController:vc animated:YES];
//    });
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
